import axios from 'axios'
import { validBlob } from '@/utils/Validate'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  withCredentials: true,
  timeout: 5000
})
/**
 * 请求拦截
 */
service.interceptors.request.use(
  config => {
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    config.headers.token = null
    return config
  }, error => {
    return Promise.reject(error)
  })
/**
 * 响应拦截
 */
service.interceptors.response.use(
  response => {
    return response
  }, error => {
    return Promise.reject(error)
  })

/**
 * GET
 * @param url
 * @param params
 * @returns {Promise<unknown>}
 * @constructor
 */
export function GET (url, params = {}) {
  return new Promise((resolve, reject) => {
    service.get(url, params).then(response => {
      if (handleApiResponseStatus(response)) resolve(response.data)
    }).catch(error => {
      if (handleHttpResponseStatus(error)) reject(error)
    })
  })
}
/**
 * POST
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 * @constructor
 */
export function POST (url = '', data = {}) {
  return new Promise((resolve, reject) => {
    service.post(url, data).then(response => {
      if (handleApiResponseStatus(response)) resolve(response.data)
    }).catch(error => {
      if (handleHttpResponseStatus(error)) reject(error)
    })
  })
}

/**
 * DOWNLOAD
 * @param params
 * @returns {Promise<unknown>}
 * @constructor
 */
export function DOWNLOAD (url = '', data = {}, fileName = '') {
  return new Promise((resolve, reject) => {
    service.post(url, data,
      { responseType: 'blob'
        // 下面这个需要后端返回length
        // onDownloadProgress (progress) {
        //   const percentCompleted = Math.round((progress.loaded * 100) / progress.total)
        //   console.log(percentCompleted)
        // }
      }
    ).then(response => {
      const isBlod = validBlob(response.data || response)
      if (isBlod) {
        const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, `${fileName}.xls`)
        } else {
          let link = document.createElement('a')
          let href = window.URL.createObjectURL(blob)
          link.href = href
          link.download = `${fileName}.xls`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(href)
        }
        resolve()
      } else {
        reject(new Error('文件格式不正确'))
        console.error('文件格式不正确')
        return false
      }
    }).catch(error => {
      if (handleHttpResponseStatus(error)) reject(error)
    })
  })
}
/**
 * 处理 response成功结果【Token失效,成功,···】【注意，不同后端成功的CODE可能不一样哦】
 * @param response
 * @returns {boolean}
 */
const handleApiResponseStatus = response => {
  const code = response.data.code
  if (code === 0 || code === 200) {
    return true
  } else if (code === 10001) {
    handleUrlRedirect()
  } else {
    console.log('----------------------------------------------------------------')
    console.log('接口：' + response.config.url)
    console.log('状态：' + response.data.code)
    console.log('报文：' + response.data.message)
    console.log('----------------------------------------------------------------')
  }
}
/**
 * 网络异常
 * @param error
 * @returns {boolean}
 */
const handleHttpResponseStatus = error => {
  console.log('----------------------------------------------------------------')
  console.log('接口：' + error.config.url)
  console.log('状态：' + error.response.data.code)
  console.log('报文：' + error.response.data.message)
  console.log('----------------------------------------------------------------')
}
/**
 * 页面重定向【Token过期,失效之类的需要重新跳转到登录页面】
 */
const handleUrlRedirect = () => {}
